package com.zhongkun.datahome.framework.web.service;

import com.zhongkun.datahome.common.core.domain.entity.SysRole;
import com.zhongkun.datahome.common.core.domain.entity.SysUser;
import com.zhongkun.datahome.common.core.domain.entity.TenantUser;
import com.zhongkun.datahome.common.core.domain.model.LoginUser;
import com.zhongkun.datahome.common.enums.TenantUserStatusEnum;
import com.zhongkun.datahome.common.enums.UserStatus;
import com.zhongkun.datahome.common.exception.ServiceException;
import com.zhongkun.datahome.common.utils.MessageUtils;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.common.utils.StringUtils;
import com.zhongkun.datahome.core.service.ISysRoleService;
import com.zhongkun.datahome.core.service.ISysUserService;
import com.zhongkun.datahome.core.service.ITenantUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ITenantUserService tenantUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username, TenantUserStatusEnum.ENABLE.getStatus());
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (TenantUserStatusEnum.DISABLE.getStatus().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);

        // 查询用户的商户权限
        List<TenantUser> tenantUserList = tenantUserService.selectTenantUserByUserId(user.getUserId());
        List<TenantUser> filterTenantUserList = tenantUserList.stream().filter(x -> SecurityUtils.getTenantId() == null || (SecurityUtils.getTenantId() != null && Objects.equals(SecurityUtils.getTenantId(), x.getTenantId()))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(filterTenantUserList)) {
            throw new ServiceException("用户没有分配商户权限");
        }
        SecurityUtils.setTenantId(filterTenantUserList.get(0).getTenantId());

        user.setRoles(sysRoleService.queryRolesByUserId(user.getUserId()));
        return createLoginUser(user, filterTenantUserList.get(0));
    }

    public UserDetails createLoginUser(SysUser user, TenantUser tenantUser) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user), tenantUser);
    }
}
